_create_deduplicate_table_sql_statement = '''
CREATE TABLE `{}` (
    `thumbnail_short_url` VARCHAR(128) NOT NULL,
    `file_name` TEXT NOT NULL,
    PRIMARY KEY (`thumbnail_short_url`),
    UNIQUE KEY `unique_thumbnail_short_url` (`thumbnail_short_url`)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
'''
_get_file_name_from_short_thumbnail_url_sql_statement = \
    'SELECT `file_name` FROM `{}` WHERE `thumbnail_short_url` = %s'
_insert_record_sql_statement = \
    'INSERT INTO `{}` (`thumbnail_short_url`, `file_name`) values (%s, %s)'
_drop_table_sql_statement = 'DROP TABLE `{}`'
_count_all_sql_statement = 'SELECT COUNT(*) FROM `{}`'
from impl.perf_stat.function_call import record_running_time


class BaiduCrawlerDeduplicationDAO:
    def __init__(self, db_connection):
        self.db_connection = db_connection
        table_name = self.db_connection.table_names['deduplication_table_name']
        self._create_deduplicate_table_sql_statement = _create_deduplicate_table_sql_statement.format(table_name)
        self._get_file_name_from_short_thumbnail_url_sql_statement = _get_file_name_from_short_thumbnail_url_sql_statement.format(table_name)
        self._insert_record_sql_statement = _insert_record_sql_statement.format(table_name)
        self._drop_table_sql_statement = _drop_table_sql_statement.format(table_name)
        self._count_all_sql_statement = _count_all_sql_statement.format(table_name)

    def create_table(self):
        self.db_connection.cursor.execute(self._create_deduplicate_table_sql_statement)

    def drop_table(self):
        self.db_connection.cursor.execute(self._drop_table_sql_statement)

    @record_running_time
    def get_file_name(self, thumbnail_short_url: str):
        self.db_connection.cursor.execute(self._get_file_name_from_short_thumbnail_url_sql_statement, (thumbnail_short_url,))
        result = self.db_connection.cursor.fetchall()
        assert len(result) == 0 or len(result) == 1
        if len(result) == 0:
            return None
        return result[0][0]

    @record_running_time
    def insert(self, thumbnail_short_url: str, file_name: str):
        self.db_connection.cursor.execute(self._insert_record_sql_statement, (thumbnail_short_url, file_name))

    @record_running_time
    def insert_multiple(self, records):
        self.db_connection.cursor.executemany(self._insert_record_sql_statement, records)

    @record_running_time
    def count_all(self):
        self.db_connection.cursor.execute(self._count_all_sql_statement)
        result = self.db_connection.cursor.fetchall()
        assert len(result) == 1
        return result[0][0]
